<template>
  <div class="page-Body">
    <div>
      <h2 class="page-title">空间管理</h2>
      <!-- 表单 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="空间名称">
          <el-input
            v-model="formInline.name"
            placeholder="请输入空间名称"
            clearable
            style="width: 300px"
            v-noSpace
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="Searchhh">搜索</el-button>
          <el-button @click="Reset">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 新增对话框组件 -->
      <el-button
        plain
        @click="AddOpenDialog"
        class="el-DiaButton"
        type="primary"
      >
        添加
      </el-button>
      <AddSpace_Dialog
        @confirm="AddConfirm"
        @cancel="AddClose"
        :dialogAdd="dialogAdd"
      />

      <!-- 表格 -->
      <el-table
        ref="myTableRef"
        :data="tableData"
        border
        stripe
        fit
        empty-text="暂无数据"
        show-header
        v-loading="loading"
        size="default"
        element-loading-text="Loading..."
        :header-cell-style="{ background: '#e7e1fb' }"
        style="width: 100%"
        max-height="540px"
      >
        <el-table-column prop="spaceId" label="序号" />
        <el-table-column prop="spaceId" label="空间ID" />
        <el-table-column prop="name" label="空间名称" width="300" />
        <el-table-column prop="destName" label="空间地点" width="300" />
        <el-table-column prop="orderLevel" label="排序" />
        <el-table-column prop="createTime" label="添加时间" />
        <el-table-column prop="state" label="状态" v-slot="scope">
          <span :style="scope.row.state === 0 ? {} : { color: 'red' }">
            {{ scope.row.state === 0 ? '展示' : '隐藏' }}
          </span>
        </el-table-column>
        <el-table-column
          align="center"
          fixed="right"
          label="操作"
          v-slot="scope"
          width="200"
        >
          <el-button
            link
            type="primary"
            @click="DetailsOpenDialog(scope.row.spaceId)"
          >
            详情
          </el-button>
          <el-button link type="primary" @click="ModifyOpenDialog(scope.row)">
            编辑
          </el-button>
          <el-button link type="danger" @click="Del(scope.row.spaceId)">
            删除
          </el-button>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页器 -->
    <div class="pagination-block">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[20, 40, 80, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 修改对话框组件 -->
    <ModifySpace_Dialog
      :dialogModify="dialogModify"
      :ModifyRow="ModifyRow"
      @confirm="ModifyConfirm"
      @cancel="ModifyClose"
    />

    <!-- 详情对话框组件 -->
    <DetailsSpace_Dialog
      :dialogDetails="dialogDetails"
      :DetailsSpaceId="DetailsSpaceId"
      @cancel="DetailsClose"
    />
  </div>
</template>

<script setup name="SpaceManagementPage">
import { getSpaceList, delSpace } from '@/api/Venue/space';
import { ref, onMounted, nextTick } from 'vue';
import AddSpace_Dialog from '@/components/Venus/space/AddSpace_Dialog.vue';
import ModifySpace_Dialog from '@/components/Venus/space/ModifySpace_Dialog.vue';
import DetailsSpace_Dialog from '@/components/Venus/space/DetailsSpace_Dialog.vue';
// 分页变量
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);

// 对话框
const dialogAdd = ref(false);
const dialogModify = ref(false);
const dialogDetails = ref(false);
const ModifyRow = ref(null);
const DetailsSpaceId = ref(null);
// 表单数据
const formInline = ref({
  name: '',
});
// 列表数据+表单校验
const tableData = ref([]);
const loading = ref(true);
const myTableRef = ref(null);
// 分页逻辑
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  // 根据是否有搜索条件决定调用哪个方法
  if (hasSearchConditions()) {
    Searchhh();
  } else {
    SpaceList();
  }
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  // 根据是否有搜索条件决定调用哪个方法
  if (hasSearchConditions()) {
    Searchhh();
  } else {
    SpaceList();
  }
};
// 获取列表
const SpaceList = async () => {
  loading.value = true;
  const res = await getSpaceList({
    current: currentPage.value,
    size: pageSize.value,
    query: {},
  });
  if (res.data.code === 200) {
    tableData.value = res.data.data.items;
    total.value = res.data.data.counts || 0;
    loading.value = false;
  }
};
// 检查搜索条件是否为空
const hasSearchConditions = () => {
  const { name } = formInline.value;
  return name;
};
// 搜索
const Searchhh = async () => {
  if (!hasSearchConditions()) {
    ElMessage({
      message: '请至少输入一个搜索条件',
      type: 'warning',
    });
    return;
  }

  try {
    loading.value = true;
    const res = await getSpaceList({
      current: currentPage.value,
      size: pageSize.value,
      query: { ...formInline.value },
    });

    if (res.data.code === 200) {
      tableData.value = res.data.data.items;
      total.value = res.data.data.counts || 0;
    }
  } catch (error) {
    console.error('搜索失败:', error);
  } finally {
    loading.value = false;
  }
};
// 重置
const Reset = () => {
  // 如果当前已经是空值状态，直接返回
  if (formInline.value.name === '') {
    return;
  }
  formInline.value = {
    name: '', // 明确设置为空字符串
  };
  currentPage.value = 1; // 重置页码
  SpaceList();
};

// 删除
const Del = async (id) => {
  console.log('删除', id);
  // eslint-disable-next-line no-undef
  ElMessageBox.confirm('确定删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const res = await delSpace(id);
      if (res.data.code === 200) {
        // eslint-disable-next-line no-undef
        ElMessage({
          message: '删除成功',
          type: 'success',
        });
        SpaceList();
      } else {
        // eslint-disable-next-line no-undef
        ElMessage({
          message: res.data.msg,
          type: 'warning',
        });
      }
    })
    .catch(() => {});
};

// 添加功能对话框
const AddOpenDialog = () => {
  dialogAdd.value = true;
};

const AddConfirm = () => {
  SpaceList();
};
const AddClose = () => {
  dialogAdd.value = false;
};

// 修改功能对话框
const ModifyOpenDialog = (row) => {
  ModifyRow.value = { ...row }; // 先设置数据
  nextTick(() => {
    dialogModify.value = true; // 再打开对话框
  });
};

const ModifyConfirm = () => {
  dialogModify.value = false;
  SpaceList();
};
const ModifyClose = () => {
  dialogModify.value = false;
};

// 详情功能对话框
const DetailsOpenDialog = (id) => {
  console.log('详情', id);
  DetailsSpaceId.value = id; // 先设置ID
  nextTick(() => {
    dialogDetails.value = true; // 再打开对话框
  });
};
const DetailsClose = () => {
  dialogDetails.value = false;
};

onMounted(() => {
  SpaceList();
});
</script>

<style lang="scss" scoped>
.el-table {
  flex: 1;
}
</style>
